package written;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author TANGYE
 * @date 2021/2/24 8:11 下午
 **/

public class Two{
    private static final Lock lock = new ReentrantLock();
    // 奇数条件
    private static final Condition jNumCondition = lock.newCondition();
    // 偶数条件
    private static final Condition oNumCondition = lock.newCondition();

    private static int num = 1;
    private static final int MAX_NUM = 100;

    public static void main(String[] args){
        Thread threadOne = new Thread(Two::printJ);
        Thread threadTwo = new Thread(Two::printO);
        threadOne.setName("JThread");
        threadTwo.setName("OThread");
        threadOne.start();
        threadTwo.start();
    }

    /*
     * 奇数线程打印
     */
    private static void printJ(){
        try{
            lock.lock();
            while(num <= MAX_NUM){
                // 奇数线程遇到偶数就阻塞，等待唤醒
                if (num % 2 == 0){
                    jNumCondition.await();
                }
                StringBuilder sb = new StringBuilder();
                sb.append("奇数线程打印：").append(num);
                num++;
                System.out.println(sb.toString());
                oNumCondition.signal();
            }

        } catch(Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    /*
     * 偶数线程打印
     */
    private static void printO(){
        try{
            lock.lock();
            while(num <= MAX_NUM){
                // 偶数线程遇到奇数就阻塞，等待唤醒
                if (num % 2 != 0){
                    oNumCondition.await();
                }
                StringBuilder sb = new StringBuilder();
                sb.append("偶数线程打印：").append(num);
                num++;
                System.out.println(sb.toString());
                jNumCondition.signal();
            }

        } catch(Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}
